<template>
	<view class="big_box">
		<view class="search">
			<u-search placeholder="搜索" v-model="keyword" @custom="searchMenu"></u-search>
		</view>
		<view class="menu">
			<view class="menu_item" v-for="item in menuData" :key="item.id" @click="go_menus(item)">
				<image :src="item.image" mode=""></image>
				<view class="text">
					{{ item.name }}
				</view>
			</view>
		</view>
		<view class="banner">
			<image src="/static/index_image/banner.png" mode="widthFix"></image>
		</view>
		<view class="notice">
			<u-notice-bar bgColor="#7dc5eb" color="#fff" :text="notice"></u-notice-bar>
		</view>
		<view class="list">
			<view class="list_item" v-for="item in listData" :key="item.id">
				<view class="left">
					<image :src="item.image" mode=""></image>
					<view class="sub_text">
						<view class="title">
							{{ item.name }}
						</view>
						<view class="desc">
							{{ item.descript }}
						</view>
					</view>
				</view>
				<u-button type="primary" class="custom-style" shape="circle" :plain="true"
					@click="go_add(item)">入群</u-button>
			</view>
		</view>

		<!-- 微信授权弹窗 - 移到页面底部 -->
		<!-- <u-modal :show="showLoginModal" title="微信授权登录" :show-cancel-button="false" confirm-button confirm-text="微信一键登录"
			@confirm="handleWechatAuth" class="bottom-modal">
			<view class="modal-content">
				<image src="/static/wechat.png" mode="aspectFit" class="wechat-icon"></image>
				<view class="modal-text">欢迎使用同城搭子平台，请先进行微信授权登录</view>
			</view>
		</u-modal> -->
		<u-popup :show="showLoginModal" mode="bottom" :round="20" title="微信授权登录" class="bottom-modal">
			<view class="modal-content">
				<image src="/static/logo.png" mode="aspectFit" class="wechat-icon"></image>
				<view class="modal-text">欢迎使用同城搭子平台，请先进行微信授权登录</view>
				<button class="wx-login-btn" @click="handleWechatAuth" :loading="wxAuthLoading">
					<text>微信一键登录</text>
				</button>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import {
		mapGetters
	} from "vuex";
	import api from '@/api/index.js'
	import request from '@/utils/request.js'
	import user from "@/api/user.js";
	// 配置常量
	const WECHAT_CONFIG = {
		appid: 'wx6bd80db273bdbad9',
		backendUrl: 'https://d-dazi.bigchun.com/',
		callback: {
			path: '#/pages/index/index', // 修改回调路径为首页
			fullUrl: 'https://d-dazi.bigchun.com/#/pages/index/index'
		},
		sessionStorageKey: 'wx_auth_state',
		scope: 'snsapi_userinfo'
	};
	export default {
		data() {
			return {
				keyword: '',
				menuData: [],
				notice: '本群是同城高质量搭子群，每天邀请大量女嘉宾进群，欢迎多来点高质量的男性，高质量人群入搭子群。聊天搭子，健身搭子，游戏搭子，运动搭子，吃饭搭子，电影搭子……',
				listData: [],
				showLoginModal: false, // 控制登录弹窗显示
				wxAuthLoading: false
			}
		},
		computed: mapGetters(['isLogin', 'uid', 'userInfo']),
		onLoad() {
			// 检查微信回调
			this.checkWechatCallback();
		},
		onShow() {
			const params = new URLSearchParams(window.location.search);
			let zhituiId = params.get('zhitui_id');
			if (!zhituiId) {
				const hashParams = window.location.hash.split('?')[1];
				if (hashParams) {
					const hashSearchParams = new URLSearchParams(hashParams);
					zhituiId = hashSearchParams.get('zhitui_id');
				}
			}
			if (!uni.getStorageSync('zhitui_id')) {
				uni.setStorageSync('zhitui_id', zhituiId)
			}

			// 如果没有token，检查是否需要显示登录弹窗
			if (!uni.getStorageSync('token') && !this.showLoginModal && !params.get('code')) {
				// 延迟显示弹窗，让页面先加载完成
				// setTimeout(() => {
				// 	this.getUserinfo();
				// }, 500);
				console.log('没有token');
				api.getUserinfo().then(res => {
					if (res.response.statusCode == 200) {
						return
					} else {
						// 显示登录弹窗
						this.showLoginModal = true;
					}
				}).catch(err => {
					console.error(err);
					// 请求出错时显示登录弹窗
					console.log('请求出错时显示登录弹窗');
					this.showLoginModal = true;
				})
			}else{
				this.getProvinceList();
				this.getGroupList();
				this.showLoginModal =false;
			}
		},
		mounted() {
			// 监听全局登录弹窗事件
			uni.$on('showLoginModal', () => {
				this.showLoginModal = true;
			});
		},
		destroyed() {
			// 组件销毁时移除事件监听
			uni.$off('showLoginModal');
		},
		methods: {
			getUserinfo() {
				api.getUserinfo().then(res => {
					if (res.response.statusCode == 200) {
						console.log('获取数据');
						this.getProvinceList();
						this.getGroupList();
						this.showLoginModal =false;
					} else {

						// 显示登录弹窗
						this.showLoginModal = true;
					}
				}).catch(err => {
					console.error(err);
					// 请求出错时显示登录弹窗
					console.log('请求出错时显示登录弹窗');
					this.showLoginModal = true;
				})
			},
			// 检查微信回调参数
			checkWechatCallback() {
				// #ifdef H5
				const params = new URLSearchParams(window.location.search);
				console.log(params, 'params');
				const code = params.get('code');
				const state = params.get('state');

				if (code && state) {
					// 验证state防止CSRF攻击
					const savedState = sessionStorage.getItem(WECHAT_CONFIG.sessionStorageKey);
					sessionStorage.removeItem(WECHAT_CONFIG.sessionStorageKey);
					let zhituiId = uni.getStorageSync('zhitui_id');
					console.log('检测到微信回调参数:', {
						code,
						state,
						zhituiId
					});
					this.exchangeWxCode(code, zhituiId);

					// 清除URL中的code参数
					this.cleanUrlParams();
				}
				// #endif
			},
			// 清除URL中的参数
			cleanUrlParams() {
				const cleanUrl = window.location.pathname;
				window.history.replaceState({}, document.title, cleanUrl);
			},
			// 微信授权处理
			handleWechatAuth() {
				try {
					this.wxAuthLoading = true;

					// #ifdef H5
					const state = 'STATE';
					sessionStorage.setItem(WECHAT_CONFIG.sessionStorageKey, state);

					const wxAuthUrl =
						`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${WECHAT_CONFIG.appid}&redirect_uri=${encodeURIComponent(`${WECHAT_CONFIG.backendUrl}${WECHAT_CONFIG.callback.path}`)}&response_type=code&scope=${WECHAT_CONFIG.scope}&state=${state}&connect_redirect=1#wechat_redirect`;

					location.replace(wxAuthUrl);
					// #endif

				} catch (error) {
					console.error('微信登录跳转失败:', error);
					this.wxAuthLoading = false;
				}
			},
			// 用code换取token
			async exchangeWxCode(code, zhituiId) {
				try {
					const res = await user.userThirdLogin({
						code: code,
						platform: "wechat",
						zhitui_id: zhituiId || 0, //分享id,在别人扫分享出去的图上的二维码的时候拿到的后缀zhitui_id
					});
					console.log('登录接口运行');
					// 立即清除URL参数
					this.cleanUrlParams();
					const userData = res.data.data;
					console.log(userData, 'userData');
					const token = userData.userinfo.token
					const userInfo = userData.userinfo
					const thirdInfo = userData.thirdinfo
					console.log(token, 'token');
					console.log(userInfo, 'userInfo');
					uni.setStorageSync('token', token);
					uni.setStorageSync('userInfo', userInfo);
					if (thirdInfo) {
						uni.setStorageSync('thirdInfo', thirdInfo);
					}
					// 更新Vuex状态
					this.$store.commit('LOGIN', {
						token,
						uid: userInfo.id || userInfo.uid
					});
					this.$store.commit('UPDATE_USERINFO', userInfo);

					// 隐藏登录弹窗
					this.showLoginModal = false;
					// 重新获取数据
					this.getUserinfo();
				} catch (error) {
					console.error("微信登录失败", error);
					// 即使失败也清除URL参数
					this.cleanUrlParams();
					// 显示登录弹窗以便用户重试
					this.showLoginModal = true;
				} finally {
					this.wxAuthLoading = false;
				}
			},
			//搜索
			searchMenu() {
				this.getProvinceList()
			},
			//获取省
			getProvinceList() {
				api.getProvinceList({
					keywords: this.keyword
				}).then(res => {
					if (res.response.statusCode == 200) {
						this.menuData = res.data.data
					}
				}).catch(err => {
					console.error(err)
				})
			},
			//获取群
			getGroupList() {
				api.getGroupList({
					cid: 1
				}).then(res => {
					if (res.response.statusCode == 200) {
						this.listData = res.data.data
					}
				}).catch(err => {
					console.error(err)
				})
			},

			//选择城市
			go_menus(item) {
				console.log(item, '选择城市')
				uni.navigateTo({
					url: '/pages/index/seach?data=' + JSON.stringify(item)
				})
			},
			//加群
			go_add(item) {
				console.log(item, '加群')
				// 检查是否已登录，如果未登录则显示登录弹窗
				if (!uni.getStorageSync('token')) {
					this.showLoginModal = true;
				} else {
					uni.navigateTo({
						url: '/pages/index/pay?data=' + JSON.stringify(item)
					})
				}
			}
		}
	};
</script>

<style lang="scss" scoped>
	@mixin flex-center-between {
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	@mixin flex-center-column {
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.big_box {
		padding: 1rem;

		.menu {
			width: 100%;
			display: flex;
			flex-wrap: wrap;
			gap: 1rem 2.2rem;
			margin-top: 1.5rem;
			// justify-content: space-between;

			.menu_item {
				width: 12%;
				@include flex-center-column;

				image {
					width: 2.2rem;
					height: 2.2rem;
				}

				.text {
					font-size: 14px;
				}
			}
		}

		.banner {
			width: 100%;
			margin-top: 1.5rem;

			image {
				width: 100%;
			}
		}

		.list {
			display: flex;
			flex-direction: column;
			width: 100%;

			.list_item {
				@include flex-center-between;
				margin: 0.5rem 0;

				.left {
					display: flex;
					align-items: center;

					image {
						width: 3rem;
						height: 3rem;
						border-radius: 0.8rem;
					}

					.title {
						font-size: 1rem;
						font-weight: 600;
						color: #191919;
					}

					.desc {
						font-size: 0.8rem;
						color: #7e7e7e;
					}
				}

				.custom-style {
					width: 4rem;
					height: 1.5rem;
					line-height: 1.5rem;
					font-size: 0.8rem;
					margin: 0;
				}
			}
		}
	}

	// 底部弹窗样式优化

	.modal-content {
		display: flex;
		flex-direction: column;
		align-items: center;
		.wechat-icon{
			width: 100rpx;
			height: 100rpx;
			border-radius: 20rpx;
			margin-top: 30rpx;
		}
		.modal-text{
			font-size: 24rpx;
			color: #7e7e7e;
			margin: 30rpx 0;
		}
	}

	.wx-login-btn {
		width: 60%;
		height: 90rpx;
		line-height: 90rpx;
		border-radius: 45rpx;
		background-color: #07C160;
		color: #fff;
		font-size: 32rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		margin-bottom: 40rpx;

		.wx-icon {
			width: 40rpx;
			height: 40rpx;
			margin-right: 15rpx;
		}

		&:after {
			border: none;
		}
	}

	/* 添加动画效果 */
	@keyframes pulse {
		0% {
			transform: scale(1);
		}

		50% {
			transform: scale(1.05);
		}

		100% {
			transform: scale(1);
		}
	}

	/* 确认按钮样式优化 */
	::v-deep.u-modal__button-group {
		padding: 20rpx 30rpx 40rpx;
	}

	::v-deep .u-modal__button-group__wrapper__text {
		background-color: #07c160 !important;
		color: #fff !important;
		font-size: 32rpx !important;
		height: 96rpx !important;
		line-height: 96rpx !important;
		border-radius: 48rpx !important;
		font-weight: 500 !important;
	}
</style>